package com.bootdo.clouddo.security;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.bootdo.clouddo.domain.user.QaUsers;
import com.bootdo.clouddo.service.user.IUserRegisterService;
import com.bootdo.clouddo.service.user.IUserService;
import com.bootdo.clouddo.service.user.WxService;
import com.bootdo.clouddo.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @author 
 *
 */
public class AppUserDetailServiceImpl implements UserDetailsService {
	
	@Autowired
	private IUserService userSerivce;

	@Autowired
	private IUserRegisterService registerService;
	
	@Autowired
	private WxService wxService;

	@Override
	public QaUsers loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		HttpServletRequest ras = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String loginWay = ras.getParameter("loginWay");
		QaUsers user = null;
		if(StringUtils.equals(QaUsers.LOGIN_WAY_SMS, loginWay)){
			user = userSerivce.findByMobile(userName);				//短信验证码登陆
		}else if(StringUtils.equals(QaUsers.LOGIN_WAY_WXOPENID, loginWay)){
			user = userSerivce.selectByWxOpenId(userName);
		}else if(StringUtils.equals(QaUsers.LOGIN_WAY_WXCODE, loginWay)) {
			// 通过code换区openId
			WxMaJscode2SessionResult sessionInfo = wxService.getSessionInfoByCode(userName);
			if(sessionInfo == null)
				return null;
			// 通过openId查询用户
			user = userSerivce.selectByWxOpenId(sessionInfo.getOpenid());
			// 如果用户为空，则创建用户
			if(user == null)
				user = registerService.createByWx(sessionInfo);
			// 重置sessionKey
			user.setWxSessionKey(sessionInfo.getSessionKey());
			System.out.println("开始登录，SessionKey：" + user.getWxSessionKey());
		}else{ 
			loginWay = QaUsers.LOGIN_WAY_PWD;
			user = userSerivce.selectByUserNameOrMobile(userName); //用户名和手机号均可登陆
		}
		if(user != null)
			user.setCurrentLoginWay(loginWay);
		return user;
	}
}
